<template>
  <div>
    <div class="topSearch">
      <p>
        <el-input size="small" style="width: 200px" placeholder="按店铺名称搜索" clearable
                  v-model="params.storeName"></el-input>
      </p>
      <p>
        <el-select size="small" style="width: 200px" placeholder="按订单类型搜索" clearable v-model="params.orderType">
          <el-option label="补单" :value="2"></el-option>
          <el-option label="新增" :value="1"></el-option>
        </el-select>
      </p>
      <p>
        <el-select size="small" style="width: 200px" placeholder="按付款方式搜索" clearable v-model="params.paymentMethod">
          <el-option
              v-for="(item, index) in payTypeList"
              :key="index"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <p>
        <el-select size="small" style="width: 200px" placeholder="按品牌搜索" v-model="params.systemType">
          <el-option v-for="(a,i) in systemList" :value="a.id" :label="a.systemName" :key="i"></el-option>
        </el-select>
      </p>
      <p>
        <el-select size="small" style="width: 200px" placeholder="按仓库搜索" v-model="params.area">
          <el-option v-for="(a,i) in areaData" :value="a.area" :label="a.areaName" :key="i"></el-option>

        </el-select>
      </p>

      <p>
        <el-button size="small" type="primary" @click="_search">搜 索</el-button>
        <el-button size="small" type="info" @click="_reset">重 置</el-button>
        <el-button size="small" type="primary" @click="_add" v-if="authority.includes(231)">新增材料订单</el-button>
      </p>
    </div>
    <div class="centerTable">
      <el-table
          :data="materialData" border
          v-loading="loading"
          height="calc(100vh - 250px)"
          :cellStyle="{ textAlign: 'center', 'font-size': '14px' }"
          :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
          fontSize: '13px'
        }"
      >
        <el-table-column type="index" label="序号" width="60px"></el-table-column>
        <el-table-column prop="storeName" label="店铺名称" width="180px" show-overflow-tooltip></el-table-column>
        <el-table-column prop="orderType" label="订单类型">
          <template v-slot:default="scope">
            <span v-if="scope.row.orderType==1">新增</span>
            <span v-if="scope.row.orderType==2">补单</span>
            <span></span>
          </template>
        </el-table-column>
        <!--        <el-table-column prop="paymentMethodName" label="付款方式"></el-table-column>-->
        <el-table-column prop="materialPayMoney" label="材料实付金额">
          <template v-slot:default="scope">
            <el-link type="primary" style="text-decoration: underline" @click="showDetail(scope.row)">
              {{ scope.row.materialPayMoney }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="materialPlaceMoney" label="材料下单金额"></el-table-column>
        <el-table-column prop="materialPoorMoney" label="材料差额"></el-table-column>
        <el-table-column prop="systemName" label="品牌"></el-table-column>
        <el-table-column prop="areaName" label="仓库"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150px" show-overflow-tooltip></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column prop="a" label="操作">
          <template v-slot:default="scope">
            <el-link style="font-size: 13px"
                     v-if="authority.includes(232)"
                     type="primary" @click="collect(scope.row)">
              补单
            </el-link>
            <!--            <el-link style="font-size: 13px;margin-left: 15px"-->
            <!--                     type="success" @click="addOrder(scope.row)">-->
            <!--              补单-->
            <!--            </el-link>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="padding: 20px 0"
          align="right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
      >
      </el-pagination>
    </div>
    <el-dialog :visible.sync="addDialog" title="新增材料订单" center width="40%" top="50px">
      <div style="display: flex;flex-direction: column;align-items: center" class="box">
        <p><span>材料信息：</span>
          <el-input size="small" type="textarea" @input="getTxt" style="width: 350px" placeholder="请输入材料信息"
                    v-model="txt"></el-input>
        </p>
        <p><span>店铺名称：</span>
          <el-input size="small" style="width: 350px" placeholder="请输入店铺名称" v-model="data.storeName"></el-input>
        </p>
        <p><span>付款方式：</span>
          <el-select size="small" style="width: 350px" placeholder="请选择付款类型" v-model="data.paymentMethod">
            <el-option
                v-for="(item, index) in payTypeList"
                :key="index"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </p>
        <p><span>订单类型：</span>
          <el-select size="small" style="width: 350px" placeholder="请选择订单类型" v-model="data.orderType">
            <el-option label="新增" value="1"></el-option>
            <el-option label="补单" value="2"></el-option>
          </el-select>
        </p>
        <p><span>材料下单金额：</span>
          <el-input size="small" style="width: 350px" placeholder="请输入材料下单金额"
                    v-model="data.materialPlaceMoney"></el-input>
        </p>
        <p><span>材料付款金额：</span>
          <el-input size="small" style="width: 350px" placeholder="请输入材料付款金额"
                    v-model="data.materialPayMoney"></el-input>
        </p>
        <p><span>品牌：</span>
          <el-select size="small" style="width: 350px" placeholder="请选择品牌名称" v-model="data.systemType">
            <el-option v-for="(a,i) in systemList" :value="a.id" :label="a.systemName" :key="i"></el-option>
          </el-select>
        </p>
        <p><span>仓库：</span>
          <el-select size="small" style="width: 350px" placeholder="请选择仓库名称" v-model="data.area">
            <el-option v-for="(a,i) in areaData" :value="a.area" :label="a.areaName" :key="i"></el-option>
          </el-select>
        </p>
        <p><span>付款时间：</span>
          <el-date-picker
              type="date"
              size="small"
              v-model="data.materialPayTime"
              style="width: 350px;"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
          </el-date-picker>
        </p>
        <p><span>备注：</span>
          <el-input size="small" type="textarea" style="width: 350px" placeholder="请输入备注"
                    v-model="data.remark"></el-input>
        </p>
        <p style="width: 450px"><span>付款凭证：</span></p>
        <el-upload
            class="upload-demo"
            drag
            :headers="headers"
            :action="`${$apiHost}/common/fileImgUrl`"
            :on-success="onSuccess"
            :show-file-list="false"
            :on-remove="_delete"
            multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <div style="display: flex;">
          <p v-for="(item,index) in proof">
            <el-image :src="'https://'+item" style="width: 35px;height: 35px"
                      :preview-src-list="proof.map((a)=>'https://'+a)"></el-image>
            <span @click="_delete(index)"
            ><el-icon class="el-icon-delete" style="font-size: 14px"></el-icon
            ></span>
          </p>
        </div>
        <!--        <div class="div" style="display: flex; align-items: center">-->
        <!--          <div-->
        <!--              v-for="(v, i) in proof"-->
        <!--              style="display: flex; align-items: flex-start; margin-right: 10px"-->
        <!--          >-->
        <!--            <el-image-->
        <!--                :key="i"-->
        <!--                style="width: 50px; height: 50px"-->
        <!--                ref="preview"-->
        <!--                :src="host + v"-->
        <!--                :preview-src-list="[host + v]"-->
        <!--            >-->
        <!--            </el-image>-->
        <!--            <div @click="deletePaiedUrl(i)">-->
        <!--              <el-icon name="delete"></el-icon>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </div>-->
        <!--        <p><span>地址：</span>-->
        <!--          <el-input size="small" style="width: 350px" placeholder="请输入地址" v-model="data.address"></el-input>-->
        <!--        </p>-->
        <!--        <p><span>联系人：</span>-->
        <!--          <el-input size="small" style="width: 350px" placeholder="请输入联系人名称" v-model="data.contactPerson"></el-input>-->
        <!--        </p>-->
        <!--        <p><span>联系电话：</span>-->
        <!--          <el-input size="small" style="width: 350px" placeholder="请输入联系人电话" v-model="data.phone"></el-input>-->
        <!--        </p>-->
      </div>
      <span slot="footer">
           <el-button size="small" @click="addDialog=false">取消</el-button>
      <el-button size="small" type="primary" @click="_submit" v-preventReClick>提交</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogOpen" title="回款录入" width="30%" center>
      <div style="display: flex;flex-direction: column;align-items: center">
        <span style="margin-bottom: 15px">订单金额： <el-input v-model="money.orderMoney" size="small" style="width: 300px"
                                                          placeholder="请输入订单金额"></el-input></span>
        <span
            style="margin-bottom: 15px">回款金额： <el-input v-model="money.amount" size="small" style="width: 300px"
                                                        placeholder="请输入回款金额"></el-input></span>
        <span style="margin-bottom: 15px">回款方式：  <el-select size="small" style="width: 300px" placeholder="请选择付款类型"
                                                            v-model="money.paymentMethod">
            <el-option
                v-for="(item, index) in payTypeList"
                :key="index"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select></span>
        <span style="margin-bottom: 15px">回款时间：<el-date-picker size="small"
                                                               style="width: 300px;" placeholder="请选择回款日期"
                                                               v-model="money.payMethodTime"
                                                               value-format="yyyy-MM-dd"></el-date-picker> </span>
        <div style="width: 71%;margin-top: 20px
">
          回款截图：<span style="color: gray; font-size: 12px"
        >(粘贴复制即可上传图片)</span
        >
          <div class="div" style="display: flex; align-items: center">
            <div
                v-for="(v, i) in fileList"
                style="display: flex; align-items: center; margin-right: 10px"
            >
              <el-image
                  :key="i"
                  style="width: 50px; height: 50px"
                  ref="preview"
                  :src="host + v"
                  :preview-src-list="[host + v]"
              >
              </el-image>
              <div @click="deletePaiedUrl(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer">
         <el-button @click="dialogOpen=false">取 消</el-button>
        <el-button type="primary" @click="onConfirm" v-preventReClick>提 交</el-button>
      </span>
    </el-dialog>
    <materialPlus ref="plusRef"></materialPlus>
    <el-dialog title="回款详情" width="80%" :close-on-click-modal="false" :visible.sync="detailDialog">
      <collect-list v-if="detailDialog" ref="collectDetail" :showBtn="showBtn" :collectName="collectNameStr"></collect-list>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import store from "../../store";
import materialPlus from "./components/materialPlus.vue";
import collectList from "./collectList.vue";

export default {
  name: "materialList",
  components: {
    materialPlus,
    collectList
  },
  data() {
    return {
      orderData: [],
      showBtn: false,
      authority: [],
      payTypeList: [],
      areaData: [],
      proof: [],
      txt: "",
      data: {
        storeName: "",
        area: "",
        materialPayMoney: "",
        materialPlaceMoney: "",
        address: "",
      },
      money: {
        paymentMethod: "",
      },
      systemList: [],
      fileList: [],
      currentPage: 1,
      collectId: "",
      totalCount: 0,
      materialData: [],
      collectNameStr:"",
      host: this.$imgHost,
      loading: false,
      detailDialog: false,
      addDialog: false,
      dialogOpen: false,
      params: {
        pageNumber: 1,
        pageSize: 20,
      }
    }
  },
  created() {
    const {authorityList = []} = this.$quinn.getStorage('userData') || {}
    this.authority = authorityList
    this.$api.areaLedgerAreaList().then(res => {
      this.areaData = res
    })
    this.getSystemType()
    this.getPayType()
    this.getList()
    document.addEventListener('paste', this.handlePaste)
  },
  computed: {
    headers() {
      return {
        token: this.token || window.$quinn.getStorage('token'),
      }
    },
  },
  methods: {
    showDetail(row) {
      this.detailDialog = true
      this.collectNameStr=row.storeName
    },
    addOrder(row) {
      this.$refs.plusRef.handleOpen(row)
    },
    _reset() {
      this.params = this.$options.data.call(this).params
    },
    onSuccess(res) {
      if (res.code === 200 && res.result) {
        this.proof.push(res.result[0])
      }
    },
    _delete(index) {
      this.proof.splice(index, 1)
    },
    getTxt(val) {
      val.replace(" ", "\n")
      this.$api.orderAutoRecognizeMaterialInfo({text: val}).then(res => {
        if (res) {
          for (let key in res) {
            if (this.data.hasOwnProperty(key)) {
              this.data[key] = res[key]
            }
          }
        } else this.$message.warning('无可用信息...')
      })

    },
    collect(row) {
      this.dialogOpen = true
      this.fileList = []
      this.money = this.$options.data.call(this).money
      this.collectId = row.orderId
    },
    onConfirm() {
      const data = {
        materialPayMoney: this.money.amount,
        prove: this.fileList[0],
        materialPlaceMoney: this.money.orderMoney,
        orderId: this.collectId,
        type: 2,
        paymentMethod: this.money.paymentMethod,
        paymentTime: this.money.payMethodTime
      }
      this.$api["orderAddMaterialPayment"](data).then(res => {
            this.$message.success('提交成功！')
            this.dialogOpen = false
            this.getList()
          }
      )
    },
    _search() {
      this.params.pageNumber = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.getList()
    },
    getList() {
      const data = this.params
      this.$api.orderGetMaterialOrderVO(data).then(res => {
        this.materialData = res.data
        this.totalCount = res.total
      })
    },
    _add() {
      this.addDialog = true
      this.txt = ''
      this.data = this.$options.data.call(this).data
      this.proof = []
    },
    async getSystemType() {
      const res = await this.$api.orderGetSystemTypeVo()
      this.systemList = res
    },
    async getPayType() {
      const res = await this.$api.orderGetPaymentMethod()
      if (res && res.length) {
        this.payTypeList = []
        this.payTypeList = res
      }
    },
    handlePaste(event) {
      if (!(this.addDialog || this.dialogOpen)) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            break;
          }
        }
      }
    },
    deletePaiedUrl(i) {
      // this.editableTabs[this.tabIndex - 1].data.fileList.splice(i, 1)
      this.proof.splice(i, 1)
      this.fileList.splice(i, 1)
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/common/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': store.state.token
        }
      })
          .then(response => {
            this.proof.push(response.data.result[0]);
            this.fileList.push(response.data.result[0]);
          })
          .catch(error => {
          });
    },
    _submit(val) {
      const data = {
        ...this.data,
        materialPayVoucher: this.proof.toString()
      }
      this.$api.addMaterialOrder(data).then(res => {
        if (res == 1) {
          this.$message.success('添加成功！')
          this.addDialog = false
          this.getList()
        }
      })
    },


  }
}
</script>

<style scoped lang="less">
/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

.topSearch {
  display: flex;
  margin-bottom: 10px;

  p {
    margin-right: 15px;
  }
}

.box {
  height: calc(100vh - 350px);
  overflow-y: auto;

  span {
    display: inline-block;
    width: 100px;
  }

  p {
    margin-bottom: 15px;
  }
}
</style>